package com.mystudy.network;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

import static sun.security.jgss.GSSToken.readInt;

/**
 * @program: infoalgorithm
 * @description: 远程控制服务器socket
 * @author: zhouzhilong
 * @create: 2019-09-16 10:59
 **/
public class RemoteControlServerSocket {

    public static void main(String[] args) throws Exception {
        read("10000");
    }


    static BufferedWriter writer;
    private static void read(final String port) throws IOException {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    ServerSocket serverSocket = new ServerSocket(Integer.parseInt(port));
                    System.out.println("before accept");
                    Socket socket = serverSocket.accept();
                    System.out.println("after accept");

                    System.out.println("before getInputStream");
                    BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());
                    System.out.println("after getInputStream");

                    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    byte[] bytes = null;
                    while (true) {
                        long s1 = System.currentTimeMillis();
                        int version = inputStream.read();
                        if (version == -1) {
                            return;
                        }
                        int length = readInt(inputStream);
                        if (bytes == null) {
                            bytes = new byte[length];
                        }
                        if (bytes.length < length) {
                            bytes = new byte[length];
                        }
                        int read = 0;
                        while ((read < length)) {
                            read += inputStream.read(bytes, read, length - read);
                        }
                        InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                        long s2 = System.currentTimeMillis();
                        Image image = ImageIO.read(byteArrayInputStream);
//                        label.setIcon(new ScaleIcon(new ImageIcon(image)));
                        long s3 = System.currentTimeMillis();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }


}
